import 'dart:convert';
import 'dart:math';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:idiom/widget/Background.dart';
import 'package:shared_preferences/shared_preferences.dart';

class GamePage extends StatefulWidget {

  @override
  State createState() {
    return new _MyAppState();
  }

}

class _MyAppState extends State<GamePage> {
  var titles = [];
  var answerOptions = [];
  var answerPrefix = ['A','B','C','D','E','F','G'];
  var size = 4;
  num score = 0;
  num money = 0.00;
  num gainMoney = 0.00;
  var scoreString = '答对 0 题';
  var moneyString = '获得 0.00 元';
  @override
  void initState() {
    mockNetworkData();
    getMoneyAndScore();
  }

  @override
  Widget build(BuildContext context) {
    final size =MediaQuery.of(context).size;
    final height =size.height;

    return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text("填成语"),
        ),
        body: new SingleChildScrollView(
         child: new Column(
           children: [
             Column(
               crossAxisAlignment: CrossAxisAlignment.center,
               //主轴方向对齐
               mainAxisAlignment: MainAxisAlignment.spaceBetween,
               children: <Widget>[
                 SizedBox(
                   height: height - 220,
                   child: test(context),
                 ),
               ],
             ),
             Row(
               children: getButton(),
             ),
             Container(
               padding: EdgeInsets.all(5.0),
               child: Row(
                   children: <Widget>[
                     Expanded(
                       child: new Text(scoreString),
                     ),
                     Expanded(
                       child: new Text(moneyString),
                     ),
                   ]
               ),
             )
           ],
         ),
        )
    );
  }

  List<Widget> getButton() {
    List<Widget> buttons = [];
    for (var i = 0; i < answerOptions.length; i++) {
      var answer = answerOptions[i];
      buttons.add(Expanded(
        child: Container(
          margin: EdgeInsets.all(5.0),
          child: new RaisedButton(
            color: Colors.blue,
            highlightColor: Colors.blue[700],
            colorBrightness: Brightness.dark,
            splashColor: Colors.grey,
            child: Text(answerPrefix[i] + '.' + answer['name']),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
            onPressed: () {
              if (answer['answer']) {
                getMoney();
                getScore();
              } else {
                showAlertFailedDialog();
              }
            },
          ),
        )
        ),
      );
    }
    return buttons;
  }

  Widget test(BuildContext context) {
    return new GridView.builder(
      itemCount: titles.length,
      itemBuilder: this._itemBuilderFunc,
      padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4
      ),
    );
  }

  Widget _itemBuilderFunc(BuildContext context, int index) {
    Title title = titles[index];
    if (title.type != 0) {
      return getTitleWidget(title.name);
    } else {
      return Center();
    }
  }

  Widget getTitleWidget(title) {
    return Center(
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          CustomPaint(
            size: Size(200, 200),
            painter: Background(),
          ),
          Text(
            title,
            style: TextStyle(fontSize: 60),
          )
        ],
      ),
    );
  }

  mockNetworkData() async {
    final response =
    await http.get("http://cm.gamemail.cn/idiom/getGame");
    final result = response.body;
    getDate(result);
  }

  getDate(var data) {
    var answer = json.decode(data)['data']['answer'];
    var idiomKeywords = json.decode(data)['data']['idiomKeywords'];

    var cross = idiomKeywords[0];
    var vertical = idiomKeywords[1];

    String idiom1 = cross['name'].trim();
    int position1 = cross['position'] - 1;
    String idiom2 = vertical['name'].trim();
    int position2 = vertical['position'] - 1;

    String dz = "霸";

    var answerOptions = [];
    for( var i = 0; i < answer.length; i++) {
      if (answer[i]['answer']) {
        dz = answer[i]['name'].trim();
      }
    }

    var titles = [];

    var sss = idiom1.length * idiom2.length;

    Title blank = new Title('', 1);

    int row = 0;
    int column = 0;
    for( var i = 0; i < sss; i++) {
      if (i % size == 0) {
        row++;
      }
      if (i % size == position1) {
        String i2 = idiom2[row-1];
        if (dz != i2) {
          titles.add(new Title(i2, 2));
        } else {
          if (!titles.contains(blank)) {
            titles.add(blank);
            column++;
          }
        }
      } else if (row == position2 + 1) {
        String i1 = idiom1[column];
        titles.add(new Title(i1, 2));
        column++;
      } else {
        titles.add(new Title('', 0));
      }
    }

    setState(() {
      this.titles = titles;
      this.answerOptions = answer;
    });
  }


  showToast(msg) {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.black45,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  var honbao = [1.22, 1.99, 1.66, 1.88, 2.66, 2.88];
  var honbao2 = [0.01, 0.01];
  var honbao3 = [0.00001, 0.00001];

  getMoney() async {
    setState(() {
      var rng = new Random();
      if (money > 95 && money <= 99) {
        gainMoney = 0.01;
      } else if (money > 99) {
        gainMoney = 0.00001;
      } else if (money > 99.99) {
        gainMoney = 0.00;
      } else {
        gainMoney = honbao[rng.nextInt(honbao.length - 1)];
      }
      showAlertSuccessDialog();
      money = NumUtil.add(money, gainMoney);
      saveMoney();
      moneyString = '获得 ' + money.toString() + ' 元';
    });
  }

  getScore() {
    setState(() {
      if (score == null) {
        score = 0;
      }
      score++;
      saveScore();
      scoreString = '答对 ' + score.toString() + ' 题';
    });
  }

  saveScore() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    print(score);
    await prefs.setInt('score', score);
  }

  saveMoney() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setDouble('money', money);
  }

  getMoneyAndScore() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    money = prefs.getDouble('money');
    score = prefs.getInt('score');

    if (money == null) {
      money = 0.00;
    }

    if (score == null) {
      score = 0;
    }

    print(score);
    setState(() {
      moneyString = '获得 ' + money.toString() + ' 元';
      scoreString = '答对 ' + score.toString() + ' 题';
    });
  }

  void showAlertSuccessDialog() {
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: new Text('回答正确'),
            //可滑动
            content: new SingleChildScrollView(
              child: new ListBody(
                children: <Widget>[
                  new Text('获得 ' + gainMoney.toString() + ' 元'),
                ],
              ),
            ),
            actions: <Widget>[
              new FlatButton(
                child: new Text('下一题'),
                onPressed: () {
                  Navigator.of(context).pop();
                  mockNetworkData();
                },
              )
            ],
          );
        });
  }

  void showAlertFailedDialog() {
    money = 0.00;
    saveMoney();
    getMoneyAndScore();
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: new Text('回答错误'),
            //可滑动
            content: new SingleChildScrollView(
              child: new ListBody(
                children: <Widget>[
                  new Text('你钱没了'),
                ],
              ),
            ),
            actions: <Widget>[
              new FlatButton(
                child: new Text('重新开始'),
                onPressed: () {
                  Navigator.of(context).pop();
                  mockNetworkData();
                },
              )
            ],
          );
        });
  }
}

class Title {
  var name;
  var type; // 0空白，1需要填写，2提示
  Title(name, type) {
    this.name = name;
    this.type = type;
  }
}

